
package com.safebox.ui;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.safebox.R;
import com.safebox.database.DatabaseHandler;
import com.safebox.database.DatabaseHelper;
import com.safebox.database.model.Message;
import com.safebox.security.DataSecurity;
import com.safebox.utils.DialogUtils;

public class InfoListActivity extends Activity {
    public static final String TAG = "==InfoListActivity==";
    
    private int user_id;

    private ListView mListView;
    // custom dialog
    private EditText mTitleEditText;

    private EditText mContentEditText;

    private SimpleCursorAdapter mAdapter;

    private static final int ADD_DIALOG_ID = 0;
    private static final int EDIT_DIALOG_ID = 1;    
    private static final int VIEW_DIALOG_ID = 2;
    private static final int DELETE_DIALOG_ID = 3;
    private static final int ABOUT_DIALOG_ID = 4;
    
    private SynchronizeTask mSynchronizeTask;
    
    private static ObjectInputStream input;
    private static ObjectOutputStream output;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user_id = getIntent().getIntExtra("userid", 0);
        setContentView(R.layout.screen_list);
        
        mListView = (ListView) findViewById(R.id.screen_listview);
        DatabaseHandler db = DatabaseHandler.getInstance(this);

        String select = DatabaseHelper.MessagesColumns.ACCOUT_ID + "=" + user_id;
        Cursor cur = db.query(DatabaseHelper.Tables.MESSAGES, null, select, null, null, null, null);
        startManagingCursor(cur);
        if (cur.getCount() == 0) {
            Toast.makeText(this, R.string.str_no_listitem_prompt, Toast.LENGTH_LONG).show();
        }

        mAdapter = new SimpleCursorAdapter(this, R.layout.list_item, cur, new String[] {
                DatabaseHelper.MessagesColumns.TITLE, DatabaseHelper.MessagesColumns.CONTENT, DatabaseHelper.MessagesColumns.DATE_MODIFIED
        }, new int[] {
                R.id.view_title, R.id.view_content, R.id.view_date, 
        });
       
        mListView.setAdapter(mAdapter);      
        

        registerForContextMenu(mListView);
        
        mListView.setTextFilterEnabled(true);

        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(InfoListActivity.this, ItemContentActivity.class);
                intent.putExtra("id", id);
               
                startActivity(intent);
            }
        });
        
        
    }  
    
    private String getAboutContent() {
        String content = null;
        try {
        PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_CONFIGURATIONS);
        String versionName = pinfo.versionName;
        
        content = getResources().getString(R.string.version) + ": " + versionName + "\n" 
                + getResources().getString(R.string.email);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.str_logout_prompt)
        .setPositiveButton(R.string.str_yes, new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {                
                InfoListActivity.this.finish();                
            }
        })
        .setNegativeButton(R.string.str_no, new DialogInterface.OnClickListener() {            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                
            }
        })
        .create().show();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.infolist_option_menu, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_add:
                showDialog(ADD_DIALOG_ID);
                return true;
            case R.id.menu_deleteAll:
                showDialog(DELETE_DIALOG_ID);               
                return true;
           /* case R.id.menu_sychronize:
                mSynchronizeTask = new SynchronizeTask();
                mSynchronizeTask.execute();                
                return true;*/
            case R.id.menu_about:
                showDialog(ABOUT_DIALOG_ID);
                return true;
           /* case R.id.menu_exit:
                showExitPromptDialog();
                return true;*/
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    private Dialog createAboutDialog() { 
        String content = getAboutContent();
        return new AlertDialog.Builder(this)
        .setTitle(R.string.about_title)
        .setMessage(content == null ? getResources().getString(R.string.about_content) : content)
        .setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                
            }
        })
        .create(); 
    }
    
    private void exit() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("exit", LoginActivity.EXIT_APPLICATION);
        startActivity(intent);
    }
    
    private void showExitPromptDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.str_exit_prompt)
        .setPositiveButton(R.string.str_yes, new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                finish();
                exit();
                
            }
        })
        .setNegativeButton(R.string.str_no, new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                
            }
        })
        .create().show();
    }
 
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        
        super.onPrepareDialog(id, dialog);
        switch (id) {
           /* case ADD_DIALOG_ID:
                removeDialog(ADD_DIALOG_ID);
                break;*/
            case EDIT_DIALOG_ID:
                removeDialog(EDIT_DIALOG_ID);
                break;
            case VIEW_DIALOG_ID:
                removeDialog(VIEW_DIALOG_ID);
                break;
            case DELETE_DIALOG_ID:
                removeDialog(DELETE_DIALOG_ID);
                break;
            case ABOUT_DIALOG_ID:
                removeDialog(ABOUT_DIALOG_ID);
        }
    }
    
    
    protected Dialog onCreateDialog(int id, Bundle args) {
        Dialog dialog = null;
        long key = -1;

        switch (id) {
            case ADD_DIALOG_ID:
                dialog = createAddCustomDialog();
                break;
            case EDIT_DIALOG_ID:
                if (args != null)
                    key = args.getLong("id");
                dialog = createEditCustomDialog(key);
                break;
            case VIEW_DIALOG_ID:
                if (args != null)
                    key = args.getLong("id");
                dialog = createViewCustomDialog(key);
                break;
            case DELETE_DIALOG_ID:
                dialog = createDeletePromptDialog();
                break;
            case ABOUT_DIALOG_ID:
                dialog = createAboutDialog();
                break;
            default:
                return super.onCreateDialog(id);
        }
        return dialog;

    }


    private Dialog createDeletePromptDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        return builder.setMessage(R.string.str_delete_all_prompt)
        .setPositiveButton(R.string.str_yes, new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel(); 
                removeAllListItem(user_id);
                
            }
        })
        .setNegativeButton(R.string.str_no, new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                
            }
        })
        .create();
        
    }



    private Dialog createViewCustomDialog(long key) {
        String title = "";
        String content = "";
        Cursor cur = DatabaseHandler.getInstance(this).query(DatabaseHelper.Tables.MESSAGES, key);
        if (cur.moveToFirst()) {
            title = cur.getString(cur.getColumnIndex(DatabaseHelper.MessagesColumns.TITLE));
            content = cur.getString(cur.getColumnIndex(DatabaseHelper.MessagesColumns.CONTENT));
        }
        cur.close();
        Dialog dialog = DialogUtils.createCustomAlertDialog(this, title, content);
        
        return dialog;

    }

    


    private Dialog createEditCustomDialog(final long key) {
        LayoutInflater factory = LayoutInflater.from(this);
        final View textView = factory.inflate(R.layout.custom_dialog, null);

        mTitleEditText = (EditText) textView.findViewById(R.id.edit_title);
        mContentEditText = (EditText) textView.findViewById(R.id.edit_content);

        Cursor cur = DatabaseHandler.getInstance(this).query(DatabaseHelper.Tables.MESSAGES, key);
        if (cur.moveToFirst()) {
            mTitleEditText.setText(cur.getString(cur
                    .getColumnIndex(DatabaseHelper.MessagesColumns.TITLE)));
            mContentEditText.setText(DataSecurity.desDecrypt(cur.getString(cur
                    .getColumnIndex(DatabaseHelper.MessagesColumns.CONTENT))));
        }
        cur.close();

        return new AlertDialog.Builder(InfoListActivity.this)
                .setTitle(R.string.str_edit_dialog_title).setView(textView)
                .setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String title = mTitleEditText.getText().toString();
                        String content = mContentEditText.getText().toString();
                       
                        changeListItem(key, title, content);
                        dialog.cancel();

                    }
                }).setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();

                    }
                }).create();

    }

    private Dialog createAddCustomDialog() {

        LayoutInflater factory = LayoutInflater.from(this);
        final View textView = factory.inflate(R.layout.custom_dialog, null);

        mTitleEditText = (EditText)textView.findViewById(R.id.edit_title);
        mContentEditText = (EditText)textView.findViewById(R.id.edit_content);

        return new AlertDialog.Builder(InfoListActivity.this)
                .setTitle(R.string.str_add_dialog_title).setView(textView)
                .setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String title = mTitleEditText.getText().toString();
                        String content = mContentEditText.getText().toString();
                        
                        addListItem(title, content);
                        dialog.cancel();

                    }
                }).setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();

                    }
                }).create();

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.infolist_context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.edit:
                
                Intent intent = new Intent(InfoListActivity.this, ItemContentActivity.class);
                intent.putExtra("id", info.id);
               
                startActivity(intent);
                return true;
            case R.id.remove:

                Log.i(TAG, "remove context menu id:" + info.id);
                removeListItem((int)(info.id));

                return true;
            default:
                return super.onContextItemSelected(item);
        }

    }

    private void removeAllListItem(long user_id)
    {
        String where = DatabaseHelper.MessagesColumns.ACCOUT_ID + "=" + user_id;
        DatabaseHandler.getInstance(this).delete(DatabaseHelper.Tables.MESSAGES, where, null);
        updateListView();
    }
    
    private void removeListItem(long item) {
        DatabaseHandler.getInstance(this).delete(DatabaseHelper.Tables.MESSAGES, item);
        updateListView();
    }

    private void addListItem(String title, String content) {
       
        DatabaseHandler.getInstance(this).insert(
                new Message(user_id, title, content));
        updateListView();

    }

    private void changeListItem(long index, String title, String content) {
        Message msg = new Message();
        msg.setTitle(title);
        msg.setContent(content);
      

        DatabaseHandler.getInstance(this).update(DatabaseHelper.Tables.MESSAGES, msg, index);

        updateListView();

    }

    private void updateListView() {
        String select = DatabaseHelper.MessagesColumns.ACCOUT_ID + "=" + user_id;
        Cursor cur = DatabaseHandler.getInstance(this).query(DatabaseHelper.Tables.MESSAGES, null, select, null, null, null, null);
        
       
        mAdapter.changeCursor(cur);
        startManagingCursor(cur);
        mAdapter.notifyDataSetChanged();
    }

    private void sychronizeContent() throws IOException {
        String ip = "10.40.73.51";
        Socket client = new Socket(ip, 8888);
           
        output = new ObjectOutputStream(client.getOutputStream());
        output.flush();
        output.writeObject("hello this is the client.");
        output.flush();
        /*input = new ObjectInputStream(client.getInputStream());     
        while (true) {
            try {
                String message = (String) input.readObject();
                Log.i("socket", "read data from server:" + message);
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
        }*/
        
    }
    
    private class SynchronizeTask extends AsyncTask<Void, Void, Integer> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            DialogUtils.showProgressBarDialog(InfoListActivity.this,
                    getResources().getString(R.string.str_synchronize_in_progress));
            
            DialogUtils.mProgressDialog.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    if (mSynchronizeTask != null) {
                        mSynchronizeTask.cancel(true);
                    }
                }
            });

        }

        @Override
        protected Integer doInBackground(Void... params) {
            Log.i("socket", "start .");
            try {
                sychronizeContent();
            } catch(Exception ex){
                ex.printStackTrace();
            }
            return 1;
        }

        @Override
        protected void onPostExecute(Integer result) {
           
            DialogUtils.dismissProgressBar();
        }

    }
}
